package org.example.day04;

/**
 * 第二章节:2.2.7:任意对象作为锁(对象监视器)
 */
public class MyThread7 {
    private String usernameParam;
    private String passwordParam;
//    private String anyString = new String();
    public void setUsernamePassword(String username,String password){
        String anyString = new String(); //A线程和B线程所用的锁不是同一个对象，不能形成互斥
        try {
            //多个线程公用同一把锁,达到了互斥
            synchronized (anyString){
                System.out.println("ThreadName = " + Thread.currentThread().getName() + " beginTime = " + System.currentTimeMillis());
                usernameParam = username;
                Thread.sleep(3000);
                passwordParam = password;
                System.out.println("ThreadName = " + Thread.currentThread().getName() + " endTime = " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread7 m7 = new MyThread7();
        Thread7A ta = new Thread7A(m7);
        ta.setName("A");
        ta.start();
        Thread7B tb = new Thread7B(m7);
        tb.setName("B");
        tb.start();
    }
}

class Thread7A extends Thread{
    private MyThread7 m7;

    public Thread7A(MyThread7 m7) {
        this.m7 = m7;
    }

    @Override
    public void run() {
        m7.setUsernamePassword("a","aa");
    }
}

class Thread7B extends Thread{
    private MyThread7 m7;

    public Thread7B(MyThread7 m7) {
        this.m7 = m7;
    }

    @Override
    public void run() {
        m7.setUsernamePassword("b","bb");
    }
}